import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../utils/screen_adapter.dart';
import '../config/app_constants.dart';

class AlphabetScrollBar extends StatefulWidget {
  final List<String> alphabetList;
  final String selectedLetter;
  final Function(String) onLetterSelected;
  final Function(String, int) onLetterCountRequested;

  const AlphabetScrollBar({
    Key? key,
    required this.alphabetList,
    required this.selectedLetter,
    required this.onLetterSelected,
    required this.onLetterCountRequested,
  }) : super(key: key);

  @override
  State<AlphabetScrollBar> createState() => _AlphabetScrollBarState();
}

class _AlphabetScrollBarState extends State<AlphabetScrollBar>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  String _currentHoverLetter = '';
  bool _isScrolling = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: AppConstants.shortAnimationDuration,
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.2,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 40.w,
      height: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.9),
        borderRadius: ScreenAdapter.borderRadius(all: 8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8.r,
            offset: Offset(-2.w, 0),
          ),
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: GestureDetector(
              onPanStart: _onPanStart,
              onPanUpdate: _onPanUpdate,
              onPanEnd: _onPanEnd,
              child: ListView.builder(
                padding: ScreenAdapter.padding(vertical: 4),
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemCount: widget.alphabetList.length,
                itemBuilder: (context, index) {
                  final letter = widget.alphabetList[index];
                  return _buildLetterItem(letter, index);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建字母项
  Widget _buildLetterItem(String letter, int index) {
    final isSelected = widget.selectedLetter == letter;
    final isHovered = _currentHoverLetter == letter;
    final count = widget.onLetterCountRequested(letter, index);
    final hasItems = count > 0;

    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        final scale = (isHovered && _isScrolling) ? _scaleAnimation.value : 1.0;
        
        return Transform.scale(
          scale: scale,
          child: Container(
            height: 20.h,
            margin: ScreenAdapter.padding(vertical: 0.5),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: hasItems ? () => _onLetterTap(letter) : null,
                borderRadius: ScreenAdapter.borderRadius(all: 12),
                child: Container(
                  decoration: BoxDecoration(
                    color: isSelected 
                        ? const Color(0xFF4CAF50).withOpacity(0.2)
                        : Colors.transparent,
                    borderRadius: ScreenAdapter.borderRadius(all: 12),
                    border: isSelected 
                        ? Border.all(
                            color: const Color(0xFF4CAF50),
                            width: 1.5,
                          )
                        : null,
                  ),
                  child: Center(
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Text(
                          letter,
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontWeight: isSelected 
                                ? FontWeight.w700 
                                : FontWeight.w500,
                            color: hasItems
                                ? (isSelected 
                                    ? const Color(0xFF4CAF50)
                                    : const Color(0xFF333333))
                                : const Color(0xFFCCCCCC),
                          ),
                        ),
                        if (hasItems && count > 0)
                          Positioned(
                            right: -2.w,
                            top: -2.h,
                            child: Container(
                              width: 6.r,
                              height: 6.r,
                              decoration: BoxDecoration(
                                color: const Color(0xFF4CAF50),
                                shape: BoxShape.circle,
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // 处理滑动开始
  void _onPanStart(DragStartDetails details) {
    _isScrolling = true;
    _animationController.forward();
    _updateHoverLetter(details.localPosition);
  }

  // 处理滑动更新
  void _onPanUpdate(DragUpdateDetails details) {
    _updateHoverLetter(details.localPosition);
  }

  // 处理滑动结束
  void _onPanEnd(DragEndDetails details) {
    _isScrolling = false;
    _animationController.reverse();
    
    if (_currentHoverLetter.isNotEmpty) {
      final count = widget.onLetterCountRequested(_currentHoverLetter, 0);
      if (count > 0) {
        widget.onLetterSelected(_currentHoverLetter);
      }
    }
    
    _currentHoverLetter = '';
  }

  // 更新悬停字母
  void _updateHoverLetter(Offset localPosition) {
    final RenderBox renderBox = context.findRenderObject() as RenderBox;
    final size = renderBox.size;
    
    // 计算相对位置
    final relativeY = localPosition.dy;
    final totalHeight = size.height;
    final itemHeight = totalHeight / widget.alphabetList.length;
    
    // 计算当前字母索引
    final index = (relativeY / itemHeight).floor().clamp(0, widget.alphabetList.length - 1);
    
    if (index >= 0 && index < widget.alphabetList.length) {
      final letter = widget.alphabetList[index];
      if (_currentHoverLetter != letter) {
        setState(() {
          _currentHoverLetter = letter;
        });
        
        // 触觉反馈
        _provideFeedback();
      }
    }
  }

  // 处理字母点击
  void _onLetterTap(String letter) {
    final count = widget.onLetterCountRequested(letter, 0);
    if (count > 0) {
      widget.onLetterSelected(letter);
      _provideFeedback();
    }
  }

  // 提供触觉反馈
  void _provideFeedback() {
    // 这里可以添加触觉反馈
    // HapticFeedback.lightImpact();
  }
}

